const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');
const app = express();

// 配置CORS，允许所有来源
app.use(cors());

// 配置代理
const runningHubProxy = createProxyMiddleware({
  target: 'https://runninghub.cn',
  changeOrigin: true,
  ws: true,
  // 不进行路径重写，保持原路径
  pathRewrite: function (path, req) {
    return path;
  },
  onProxyReq: function(proxyReq, req, res) {
    // 设置Host请求头
    proxyReq.setHeader('Host', 'www.runninghub.cn');
    
    // 打印详细的请求信息，方便调试
    console.log(`[代理请求] ${req.method} ${req.url}`);
    console.log(`[请求头] Host: www.runninghub.cn`);
    
    // 如果是POST请求，打印请求体信息（但不显示敏感信息如apiKey）
    if (req.method === 'POST' && req.body) {
      const bodyCopy = {...req.body};
      if (bodyCopy.apiKey) bodyCopy.apiKey = '******'; // 隐藏API密钥
      console.log(`[请求体] ${JSON.stringify(bodyCopy, null, 2)}`);
    }
  },
  onProxyRes: function(proxyRes, req, res) {
    // 打印响应信息，方便调试
    console.log(`[代理响应] ${req.method} ${req.url} ${proxyRes.statusCode}`);
    
    // 记录响应头信息
    console.log(`[响应头] ${JSON.stringify(proxyRes.headers, null, 2)}`);
    
    // 对于错误响应，提供更详细的日志
    if (proxyRes.statusCode >= 400) {
      console.error(`[错误] 请求 ${req.url} 返回状态码 ${proxyRes.statusCode}`);
      
      // 收集响应体以记录错误详情
      let responseBody = '';
      proxyRes.on('data', function(chunk) {
        responseBody += chunk;
      });
      
      proxyRes.on('end', function() {
        try {
          // 尝试解析JSON错误响应
          const parsedBody = JSON.parse(responseBody);
          console.error(`[错误详情] ${JSON.stringify(parsedBody, null, 2)}`);
        } catch (e) {
          // 如果不是JSON，则输出原始响应
          console.error(`[错误详情] ${responseBody}`);
        }
      });
    }
  },
  // 添加错误处理
  onError: function(err, req, res) {
    console.error(`[代理错误] ${err.message}`);
    res.writeHead(500, {
      'Content-Type': 'application/json'
    });
    res.end(JSON.stringify({
      error: '代理服务器错误',
      message: err.message
    }));
  }
});

// 解析JSON请求体
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({extended: true, limit: '50mb'}));

// 配置代理路由
app.use('/api', runningHubProxy);
app.use('/task', runningHubProxy);
app.use('/uc', runningHubProxy);

// 添加测试接口
app.get('/test', (req, res) => {
  res.json({
    status: 'ok',
    message: '代理服务器运行正常'
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`代理服务器运行在 http://localhost:${PORT}`);
  console.log('代理路径:');
  console.log('  /api/* -> https://runninghub.cn/api/*');
  console.log('  /task/* -> https://runninghub.cn/task/*');
  console.log('  /uc/* -> https://runninghub.cn/uc/*');
  console.log('');
  console.log('请求示例:');
  console.log('  POST http://localhost:3000/task/openapi/create');
  console.log('  - 需要设置 Content-Type: application/json');
  console.log('  - 需要在请求体中提供 apiKey 和 workflowId');
}); 